#!/usr/bin/env node
const StockService = require('./services/stockService');
const Stock = require('./models/stock');
const { initDatabase } = require('./config/database');

// 颜色输出函数
const colors = {
  red: (text) => `\x1b[31m${text}\x1b[0m`,
  green: (text) => `\x1b[32m${text}\x1b[0m`,
  yellow: (text) => `\x1b[33m${text}\x1b[0m`,
  blue: (text) => `\x1b[34m${text}\x1b[0m`,
  cyan: (text) => `\x1b[36m${text}\x1b[0m`,
  bold: (text) => `\x1b[1m${text}\x1b[0m`
};

// 显示帮助信息
function showHelp() {
  console.log(colors.bold('\n📈 股票监控系统管理工具'));
  console.log('\n用法: node stock-manager.js [命令]\n');
  console.log('命令:');
  console.log('  status, -s     检查交易时间状态');
  console.log('  update, -u     手动更新所有股票数据');
  console.log('  list, -l       显示所有股票列表');
  console.log('  add <code>     添加新股票');
  console.log('  remove <id>    删除股票');
  console.log('  price <id>     查看股票最新价格');
  console.log('  help, -h       显示此帮助信息');
  console.log('\n示例:');
  console.log('  node stock-manager.js status');
  console.log('  node stock-manager.js update');
  console.log('  node stock-manager.js add 600000');
  console.log('  node stock-manager.js price 1');
}

// 检查交易时间状态
function checkTradingStatus() {
  const now = new Date();
  const chinaTime = new Date(now.getTime() + 8 * 60 * 60 * 1000);
  const isTradingTime = StockService.isTradingTime();
  const nextTradingTime = StockService.getNextTradingTime();
  
  console.log(colors.bold('\n📊 股票交易时间状态'));
  console.log('━'.repeat(40));
  console.log(`🕐 当前时间: ${colors.cyan(chinaTime.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }))}`);
  console.log(`📈 交易状态: ${isTradingTime ? colors.green('✅ 交易中') : colors.red('❌ 非交易时间')}`);
  
  if (!isTradingTime) {
    console.log(`⏰ 下次交易: ${colors.yellow(nextTradingTime.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }))}`);
    const waitTime = nextTradingTime.getTime() - Date.now();
    const waitHours = Math.floor(waitTime / (1000 * 60 * 60));
    const waitMinutes = Math.floor((waitTime % (1000 * 60 * 60)) / (1000 * 60));
    console.log(`⏳ 等待时间: ${colors.yellow(`${waitHours}小时${waitMinutes}分钟`)}`);
  }
  
  console.log('\n📋 交易时间说明:');
  console.log('   • 交易日: 周一至周五');
  console.log('   • 交易时间: 09:29 - 15:00');
  console.log('   • 非交易时间不会自动更新数据');
  
  return isTradingTime;
}

// 手动更新股票数据
async function manualUpdate() {
  console.log(colors.bold('\n🔄 手动更新股票数据'));
  console.log('━'.repeat(40));
  
  try {
    console.log('⏳ 正在获取股票数据...');
    const startTime = Date.now();
    const stockData = await StockService.updateAllStocks();
    const endTime = Date.now();
    
    console.log(colors.green(`✅ 更新完成！耗时 ${endTime - startTime}ms`));
    console.log(`📊 获取到 ${colors.cyan(stockData.length)} 只股票数据\n`);
    
    if (stockData.length > 0) {
      console.log('📈 更新的股票数据:');
      stockData.forEach((stock, index) => {
        const priceChange = stock.price - stock.openPrice;
        const priceChangePercent = ((priceChange / stock.openPrice) * 100).toFixed(2);
        const changeColor = priceChange >= 0 ? colors.green : colors.red;
        const changeSymbol = priceChange >= 0 ? '↗' : '↘';
        
        console.log(`  ${index + 1}. ${colors.bold(stock.name)} (${stock.code})`);
        console.log(`     💰 当前价格: ¥${colors.cyan(stock.price.toFixed(2))}`);
        console.log(`     📊 开盘价格: ¥${stock.openPrice.toFixed(2)}`);
        console.log(`     ${changeSymbol} 涨跌幅: ${changeColor(`¥${priceChange.toFixed(2)} (${priceChangePercent}%)`)}\n`);
      });
    } else {
      console.log(colors.yellow('⚠️  没有获取到股票数据'));
    }
  } catch (error) {
    console.error(colors.red(`❌ 更新失败: ${error.message}`));
  }
}

// 显示股票列表
async function listStocks() {
  console.log(colors.bold('\n📋 股票列表'));
  console.log('━'.repeat(40));
  
  try {
    await initDatabase();
    const stocks = await Stock.getAllStocks();
    
    if (stocks.length === 0) {
      console.log(colors.yellow('📭 暂无股票数据'));
      return;
    }
    
    console.log(`📊 共有 ${colors.cyan(stocks.length)} 只股票:\n`);
    
    for (const stock of stocks) {
      try {
        const latestPrice = await Stock.getLatestPrice(stock.id);
        console.log(`  ${stock.id}. ${colors.bold(stock.name)} (${stock.code})`);
        
        if (latestPrice) {
          const priceChange = latestPrice.price - latestPrice.open_price;
          const priceChangePercent = ((priceChange / latestPrice.open_price) * 100).toFixed(2);
          const changeColor = priceChange >= 0 ? colors.green : colors.red;
          const changeSymbol = priceChange >= 0 ? '↗' : '↘';
          
          console.log(`     💰 最新价格: ¥${colors.cyan(latestPrice.price.toFixed(2))}`);
          console.log(`     ${changeSymbol} 涨跌幅: ${changeColor(`¥${priceChange.toFixed(2)} (${priceChangePercent}%)`)}`);
          console.log(`     🕐 更新时间: ${new Date(latestPrice.timestamp).toLocaleString('zh-CN')}`);
        } else {
          console.log(`     ${colors.yellow('⚠️  暂无价格数据')}`);
        }
        console.log('');
      } catch (error) {
        console.log(`     ${colors.red('❌ 获取价格数据失败')}\n`);
      }
    }
  } catch (error) {
    console.error(colors.red(`❌ 获取股票列表失败: ${error.message}`));
  }
}

// 添加股票
async function addStock(code) {
  if (!code) {
    console.log(colors.red('❌ 请提供股票代码'));
    return;
  }
  
  console.log(colors.bold(`\n➕ 添加股票: ${code}`));
  console.log('━'.repeat(40));
  
  try {
    await initDatabase();
    
    // 获取股票数据
    console.log('⏳ 正在获取股票信息...');
    const stockData = await StockService.fetchStockData(code);
    
    // 添加到数据库
    const stockId = await Stock.addStock(code, stockData.name);
    
    // 添加价格记录
    await Stock.addStockPrice(
      stockId,
      stockData.price,
      stockData.openPrice,
      stockData.closePrice,
      stockData.highPrice,
      stockData.lowPrice,
      stockData.yesterdayClosePrice, // 昨日收盘价
      stockData.volume // 成交量
    );
    
    console.log(colors.green(`✅ 成功添加股票: ${stockData.name} (${code})`));
    console.log(`💰 当前价格: ¥${colors.cyan(stockData.price.toFixed(2))}`);
  } catch (error) {
    console.error(colors.red(`❌ 添加股票失败: ${error.message}`));
  }
}

// 删除股票
async function removeStock(id) {
  if (!id) {
    console.log(colors.red('❌ 请提供股票ID'));
    return;
  }
  
  console.log(colors.bold(`\n🗑️  删除股票: ID ${id}`));
  console.log('━'.repeat(40));
  
  try {
    await initDatabase();
    
    // 获取股票信息
    const stocks = await Stock.getAllStocks();
    const stock = stocks.find(s => s.id == id);
    
    if (!stock) {
      console.log(colors.red('❌ 股票不存在'));
      return;
    }
    
    // 删除股票
    await Stock.deleteStock(id);
    console.log(colors.green(`✅ 成功删除股票: ${stock.name} (${stock.code})`));
  } catch (error) {
    console.error(colors.red(`❌ 删除股票失败: ${error.message}`));
  }
}

// 查看股票价格
async function showStockPrice(id) {
  if (!id) {
    console.log(colors.red('❌ 请提供股票ID'));
    return;
  }
  
  console.log(colors.bold(`\n💰 股票价格: ID ${id}`));
  console.log('━'.repeat(40));
  
  try {
    await initDatabase();
    
    // 获取股票信息
    const stocks = await Stock.getAllStocks();
    const stock = stocks.find(s => s.id == id);
    
    if (!stock) {
      console.log(colors.red('❌ 股票不存在'));
      return;
    }
    
    console.log(`📈 ${colors.bold(stock.name)} (${stock.code})\n`);
    
    // 获取最新价格
    const latestPrice = await Stock.getLatestPrice(id);
    
    if (!latestPrice) {
      console.log(colors.yellow('⚠️  暂无价格数据'));
      return;
    }
    
    const priceChange = latestPrice.price - latestPrice.open_price;
    const priceChangePercent = ((priceChange / latestPrice.open_price) * 100).toFixed(2);
    const changeColor = priceChange >= 0 ? colors.green : colors.red;
    const changeSymbol = priceChange >= 0 ? '↗' : '↘';
    
    console.log(`💰 当前价格: ¥${colors.cyan(latestPrice.price.toFixed(2))}`);
    console.log(`📊 开盘价格: ¥${latestPrice.open_price.toFixed(2)}`);
    console.log(`📈 最高价格: ¥${colors.green(latestPrice.high_price.toFixed(2))}`);
    console.log(`📉 最低价格: ¥${colors.red(latestPrice.low_price.toFixed(2))}`);
    console.log(`${changeSymbol} 涨跌幅: ${changeColor(`¥${priceChange.toFixed(2)} (${priceChangePercent}%)`)}`);
    console.log(`🕐 更新时间: ${new Date(latestPrice.timestamp).toLocaleString('zh-CN')}`);
  } catch (error) {
    console.error(colors.red(`❌ 获取股票价格失败: ${error.message}`));
  }
}

// 主函数
async function main() {
  const args = process.argv.slice(2);
  const command = args[0];
  
  if (!command || command === 'help' || command === '-h') {
    showHelp();
    return;
  }
  
  switch (command) {
    case 'status':
    case '-s':
      checkTradingStatus();
      break;
      
    case 'update':
    case '-u':
      await manualUpdate();
      break;
      
    case 'list':
    case '-l':
      await listStocks();
      break;
      
    case 'add':
      await addStock(args[1]);
      break;
      
    case 'remove':
      await removeStock(args[1]);
      break;
      
    case 'price':
      await showStockPrice(args[1]);
      break;
      
    default:
      console.log(colors.red(`❌ 未知命令: ${command}`));
      showHelp();
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  main().catch(error => {
    console.error(colors.red(`❌ 执行失败: ${error.message}`));
    process.exit(1);
  });
}

module.exports = {
  checkTradingStatus,
  manualUpdate,
  listStocks,
  addStock,
  removeStock,
  showStockPrice
};